//
//  CallMeTypeViewController.m
//  JiuLe
//
//  Created by xcq on 15/11/11.
//  Copyright © 2015年 Fine. All rights reserved.
//
#import "ConfigDefine.h"
#import "JlUserManager.h"
#import "JLCallMeModel.h"
#import "UWDatePickerView.h"
#import "CallMeTypeTableViewCell.h"
#import "CallMeTypeViewController.h"
static NSString *cellIdentifire = @"CallMeType";
@interface CallMeTypeViewController () <UITableViewDataSource,UITableViewDelegate,UWDatePickerViewDelegate> {
    NSMutableArray *datas;
    NSString *firstTime;
    NSString *secondTime;
    UWDatePickerView* pickerView;
//    NSInteger selectTag;
   __weak CallMeTypeTableViewCell *seleteCell;
}

@end

@implementation CallMeTypeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"来电设置";
    addObserver(@selector(updateModel:), @"refreshData");
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self showNavBarWithRightTitle:nil andRightAction:nil andLeftAction:@selector(homeControllerBackTo) andRightBtnIsShow:NO];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [self SeparatorForTableView:_tableView];
    [self netRequest];
}

- (void)updateModel:(id )obj {
    BACK((^(){
        JLCallMeModel *model = nil;
        JlUserManager *manamger = [JlUserManager shareInstance];
        if ([obj isKindOfClass:[NSNotification class]]) {
            model = ((NSNotification *)obj).object;
        } else {
            model = (JLCallMeModel *)obj;
        }
        [InterfaceNetManager SetPhoneSetting:^(BOOL isSucceed,
                                               NSString *message,
                                               id data,
                                               NSError *error) {
            if (isSucceed) {
                JLLog(@"来电设置上传成功");
            } else {
                JLLog(@"来电设置上传失败");
            }
        } andParameter:@{@"userid":manamger.userInfo.userid,
                         @"type":model.type,
                         @"time":model.time}];
    }));
    
}

- (void)netRequest {
    [SVProgressHUD showWithStatus:@"加载中..."];
    datas = [NSMutableArray new];
    if ([SocketManager sharedInstance].socket.isConnected) {
        [self getDefaultCallMeData];
    } else {
        [InterfaceNetManager RequestPhoneSettingCompletion:^(BOOL isSucceed,
                                                                  NSString *message,
                                                                  id data,
                                                                  NSError *error) {
            if (isSucceed) {
                JLLog(@"%@",data);
                NSArray *dataArr;
                if (data == nil || data == [NSNull null]) {
                    dataArr = [NSArray array];
                } else {
                    dataArr  = (NSArray *)data;
                }
                for (int i = 0; i < dataArr.count; i ++) {
                    JLCallMeModel *model = [JLCallMeModel objectWithKeyValues:dataArr[i]];
                    [datas addObject:model];
                }
            }
            [self getDefaultCallMeData];

        }];
    }
}
/*

 */

- (void)getDefaultCallMeData {
    if (datas.count == 0) {
        JLCallMeModel *model1 = [NSUserDefaults objectUserForKey:UserCallMeTypeSos];
        [datas addObject:model1];
         JLCallMeModel *model2 = [NSUserDefaults objectUserForKey:UserCallMeTypeEarlyWarning];
        [datas addObject:model2];
         JLCallMeModel *model3 = [NSUserDefaults objectUserForKey:UserCallMeTypeAlarm];
        [datas addObject:model3];
         JLCallMeModel *model4 = [NSUserDefaults objectUserForKey:UserCallMeTypeFallDown];
        [datas addObject:model4];
    } else {
        NSMutableArray *arr = [NSMutableArray arrayWithArray:@[@"1",@"2",@"3",@"4"]];
        for (int i = 0; i < datas.count; i ++) {
            JLCallMeModel *model = [datas objectAtIndex:i];
            if ([model.type isEqualToString:@"1"]) { //sos
                [arr removeObject:@"1"];
            } else if ([model.type isEqualToString:@"2"]) { //EarlyWarning
                [arr removeObject:@"2"];
            } else if ([model.type isEqualToString:@"3"]) { //Alarm
                [arr removeObject:@"3"];
            } else {
                [arr removeObject:@"4"];
            }
        }
        
        for (int y = 0; y < arr.count; y ++ ) {
            if ([[arr objectAtIndex:y] integerValue] == 1) {
                JLCallMeModel *model = [NSUserDefaults objectUserForKey:UserCallMeTypeSos];
                [datas addObject:model];
            } else if ([[arr objectAtIndex:y] integerValue] == 2) {
                JLCallMeModel *model = [NSUserDefaults objectUserForKey:UserCallMeTypeEarlyWarning];
                [datas addObject:model];
            } else if ([[arr objectAtIndex:y] integerValue] == 3) {
                JLCallMeModel *model = [NSUserDefaults objectUserForKey:UserCallMeTypeAlarm];
                [datas addObject:model];
            } else {
                JLCallMeModel *model = [NSUserDefaults objectUserForKey:UserCallMeTypeFallDown];
                [datas addObject:model];
            }
        }
    }
    [self shuffleDataSource];
    if (self.tableView.delegate == nil) {
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
    }
    [self.tableView reloadData];
}

- (void)shuffleDataSource {
    datas = [NSMutableArray arrayWithArray:[datas sortedArrayUsingSelector:@selector(comparePerson:)]];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return datas.count > 0 ? datas.count : 0;
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CallMeTypeTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"CallMeTypeTableViewCell" owner:self options:nil] lastObject];
    JLLog(@"_______________________%@_______________________",cell);
    JLCallMeModel *model = [datas objectAtIndex:indexPath.row];
    cell.tag = indexPath.row;
    if ([model.time isEqualToString:@"1"] || [model.time isEqualToString:@"0"]) {
        cell.times = @[@"0800",@"2400"];
    } else {
        NSString *firstTimes = [model.time substringWithRange:NSMakeRange(0, 4)];
        NSString *lastTime = [model.time substringWithRange:NSMakeRange(4, 4)];
        cell.times = @[firstTimes,lastTime];
    }
    cell.dic = model;
    cell.action = ^(CallMeTypeTableViewCell * cellTemp){
        [self createPick];
        pickerView.title.text = @"请选择起始时间";
        seleteCell = cellTemp;
    };
   
    cell.type = [model.type intValue];

    cell.select = model.time;
    JLLog(@"%@",model);
    return cell;
}

- (void)getSelectDate:(NSString *)date type:(DateType)type {
    
    switch (type) {
        case DateTypeOfStart: {
            // TODO 日期确定选择
            if (firstTime == nil) {
                firstTime = date;
                [pickerView removeBtnClick:nil];
                [self createPick];
                pickerView.title.text = @"请选择终止时间";
                [self.view bringSubviewToFront:pickerView];
            } else if (secondTime == nil) {
                if ([date isEqualToString:firstTime]) {
                    [SVProgressHUD showErrorWithStatus:@"终止时间不能和起始时间相同!"];
                    return;
                }
                secondTime = date;
                [pickerView removeBtnClick:nil];
               
                NSString *firstTimes = [[[firstTime componentsSeparatedByString:@":"] firstObject] stringByAppendingString:[[firstTime componentsSeparatedByString:@":"] lastObject]];
                NSString *lastTimes =  [[[secondTime componentsSeparatedByString:@":"] firstObject] stringByAppendingString:[[secondTime componentsSeparatedByString:@":"] lastObject]];
                seleteCell.times = @[firstTimes,lastTimes];
                NSIndexPath *path = [_tableView indexPathForCell:seleteCell];
                JLCallMeModel *model = [datas objectAtIndex:path.row];
                model.time = [firstTimes stringByAppendingString:lastTimes];
                [self.tableView reloadData];
            
                NSString *str = nil;
                if (path.row  == 0) {
                    str = UserCallMeTypeSos;
                } else if (path.row  == 1) {
                    str = UserCallMeTypeEarlyWarning;
                } else if (path.row  == 2){
                    str = UserCallMeTypeAlarm;
                } else {
                    str = UserCallMeTypeFallDown;
                }
                [NSUserDefaults setUserObject:model forKey:str];
                [self updateModel:model];
                firstTime = nil;
                secondTime = nil;
            }
            break;
        }
        case DateTypeOfEnd:
            // TODO 日期取消选择
            break;
        default:
            break;
    }
}

- (void)createPick {
    pickerView = [UWDatePickerView instanceDatePickerView];
    pickerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    [pickerView setBackgroundColor:[UIColor clearColor]];
    pickerView.delegate = self;
    pickerView.type = DateTypeOfStart;
    pickerView.datePickerView.datePickerMode = UIDatePickerModeTime;
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"hh:mm"];
    pickerView.datePickerView.date = [formatter dateFromString:@"08:00"];
    [self.view addSubview:pickerView];
}

- (void)showPickerView {
    [UIView animateWithDuration:0.3f animations:^{
        pickerView.hidden = NO;
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 159;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}



@end
